<template>
  <div class="memo-container">
    <el-card shadow="hover" class="main-card">
      <!-- 头部 -->
      <template #header>
        <div class="header-content">
          <!-- <h1 class="title">~记录你的安排~</h1> -->
          <div class="operation-bar">
            <el-input v-model="searchQuery" placeholder="搜索" clearable style="width: 200px; margin-right: 15px;">
              <template #prefix>
                <el-icon>
                  <search />
                </el-icon>
              </template>
            </el-input>

            <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" clearable />

            <el-button type="primary" class="add-button" @click="dialogVisible = true">
              <el-icon>
                <plus />
              </el-icon>新建
            </el-button>
          </div>
        </div>
      </template>

      <!-- 备忘录列表 -->
      <div v-if="filteredMemos?.length" class="memo-list">
        <el-card v-for="memo in filteredMemos" :key="memo.id" class="memo-item" :class="`priority-${memo.priority}`">
          <div class="memo-content">
            <div class="meta-info">
              <el-tag :type="priorityTypes[memo.priority]?.type || 'info'" effect="dark" class="priority-tag">
                {{ priorityTypes[memo.priority]?.label || '低' }}
              </el-tag>
              <span class="date">{{ formatDate(memo.create_time) }}</span>
              <span class="time">{{ formatTime(memo.create_time) }}</span>
            </div>

            <div class="text">{{ memo.content }}</div>

            <div class="actions">
              <el-button type="warning" size="small" @click="handleEditMemo(memo)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteMemo(memo.id)">
                删除
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      <el-empty v-else description="暂无备忘录" />
    </el-card>

    <!-- 新建对话框 -->
    <el-dialog v-model="dialogVisible" title="新建备忘录">
      <el-form :model="newMemo">
        <el-form-item label="内容:" prop="content">
          <el-input v-model="newMemo.content" type="textarea" :rows="5" placeholder="输入内容" show-word-limit
            maxlength="500" />
        </el-form-item>

        <el-form-item label="优先级:">
          <el-select v-model="newMemo.priority">
            <el-option v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateMemo">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from '../api/axios.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { useCookies } from "vue3-cookies"

const { cookies } = useCookies();
// 响应式数据
const memos = ref([])
const searchQuery = ref('')
const selectedDate = ref('')
const dialogVisible = ref(false)
const newMemo = ref({
  eid: cookies.get("id"),
  content: '',
  priority: 2
})

// 优先级配置
const priorityOptions = [
  { value: 1, label: '高' },
  { value: 2, label: '中' },
  { value: 3, label: '低' }
]

const priorityTypes = {
  1: { type: 'danger', label: '高' },
  2: { type: 'warning', label: '中' },
  3: { type: 'success', label: '低' }
}

// 计算属性
const filteredMemos = computed(() => {
  return memos.value?.filter(memo => {
    const contentMatch = memo.content?.toLowerCase().includes(searchQuery.value.toLowerCase())
    const dateMatch = selectedDate.value ?
      formatDate(memo.create_time) === selectedDate.value :
      true
    return contentMatch && dateMatch
  }).sort((a, b) => {
    if (a.priority !== b.priority) {
      return a.priority - b.priority
    }
    return new Date(b.create_time) - new Date(a.create_time)
  })
})

// 生命周期钩子
onMounted(async () => {
  await fetchMemos()
})

// API方法
const fetchMemos = async () => {
  try {
    const response = await axios.get('memo/get', {
      params: {
        eid: cookies.get("id")
      }
    })
    memos.value = response.data.data.list?.map(item => ({
      ...item,
      create_time: new Date(item.create_time)
    }))
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('API Error:', error)
  }
}

const handleCreateMemo = async () => {
  if (!newMemo.value.content.trim()) {
    ElMessage.warning('请输入备忘内容')
    return
  }

  try {
    const response = await axios.post('memo/create', {
      employee_id: newMemo.value.eid,
      content: newMemo.value.content,
      priority: newMemo.value.priority
    })
    
    if(memos == 'undefined'){
      memos.value = []
    }
    memos.value.unshift({
      ...response.data.data,
      create_time: new Date(response.data.data.create_time)
    })

    dialogVisible.value = false
    newMemo.value = {
      eid: cookies.get("id"),
      content: '',
      priority: 2
    }
    ElMessage.success('创建成功')
  } catch (error) {
    ElMessage.error('创建失败')
    console.error('API Error:', error)
  }
}

const handleEditMemo = async (memo) => {
  try {
    const { value } = await ElMessageBox.prompt('编辑内容', '修改备忘', {
      inputValue: memo.content,
      confirmButtonText: '保存',
      cancelButtonText: '取消'
    })

    if (value && value.trim()) {
      const response = await axios.post('memo/update', {
        id: memo.id,
        employee_id: cookies.get("id"),
        content: value.trim(),
        priority: memo.priority
      })
      Object.assign(memo, response.data.data)
      memo.create_time = new Date(response.data.data.create_time)
      ElMessage.success('更新成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新失败')
      console.error('API Error:', error)
    }
  }
}

const handleDeleteMemo = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该备忘录？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.get('memo/delete', {
      params: {
        id: id
      }
    })
    memos.value = memos.value.filter(m => m.id !== id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('API Error:', error)
    }
  }
}

// 工具方法
const formatDate = (date) => {
  return date?.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
}

const formatTime = (date) => {
  return date?.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.memo-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.main-card {
  border-radius: 12px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.title {
  color: var(--el-color-primary);
  margin: 0;
  font-size: 1.5rem;
}

.operation-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.add-button {
  margin-left: auto;
}

.memo-list {
  display: grid;
  gap: 15px;
}

.memo-item {
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.memo-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.memo-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
}

.memo-item.priority-HIGH::before {
  background-color: var(--el-color-danger);
}

.memo-item.priority-MEDIUM::before {
  background-color: var(--el-color-warning);
}

.memo-item.priority-LOW::before {
  background-color: var(--el-color-success);
}

.memo-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 15px;
  color: var(--el-text-color-secondary);
  font-size: 0.9em;
}

.date {
  margin-right: auto;
}

.text {
  font-size: 1.1em;
  line-height: 1.6;
  color: var(--el-text-color-primary);
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    width: 100%;

    >* {
      width: 100%;
    }
  }

  .memo-item {
    margin: 0 -15px;
    border-radius: 0;
  }
}
</style>